"""
信访分析任务，执行结果记录相关模型
"""
from sqlalchemy import Column, Integer, String,  DateTime,  ForeignKey
from sqlalchemy.orm import relationship

from .base import Base, TimestampMixin, ActiveMixin


class PetitionRecord(Base, TimestampMixin, ActiveMixin):
    """信访记录模型"""
    
    __tablename__ = "petition_record"
    
    # 基本信息
    xh = Column(String(100), unique=True, index=True, nullable=False, comment="信访记录id")
    ccjbz = Column(String(100), comment="初重件标志")
    flnr = Column(String(100), comment="分类内容")
    tsr = Column(String(100), comment="姓名")
    xfnr = Column(String(2000), comment="投诉内容")
    ts_gk = Column(String(2000), comment="概况")
    ts_xzq = Column(String(100), comment="问题属地")
    ts_ds = Column(String(100), comment="地市")
    ts_qxs = Column(String(100), comment="区县市")
    ts_jd = Column(String(100), comment="乡镇街道")
    ts_dz = Column(String(500), comment="地址")
    ts_qxdw = Column(String(100), comment="去向单位")
    ts_dfnr = Column(String(2000), comment="答复内容")
    djsj = Column(DateTime, comment="登记时间")
    ts_bz = Column(String(1000), comment="备注")
    # 创建者
    creator_id = Column(Integer, ForeignKey('user.id'), comment="创建者ID")
    task_id = Column(Integer, ForeignKey('analysis_task.id'), nullable=True, comment="关联的分析任务ID")

    creator = Column(String(20), comment="创建者")
    
    def get_full_address(self) -> str:
        """获取完整地址"""
        parts = []
        if self.ts_ds:
            parts.append(self.ts_ds)
        if self.ts_qxs:
            parts.append(self.ts_qxs)
        if self.ts_jd:
            parts.append(self.ts_jd)
        if self.ts_dz:
            parts.append(self.ts_dz)
        return "".join(parts)
    
    def get_registration_time_display(self) -> str:
        """获取登记时间显示"""
        if self.djsj:
            return self.djsj.strftime("%Y-%m-%d %H:%M:%S")
        return "未知"
    
    def get_complaint_type_display(self) -> str:
        """获取投诉类型显示"""
        return self.flnr or "未分类"
    
    def get_region_display(self) -> str:
        """获取区域显示"""
        return f"{self.ts_ds}-{self.ts_qxs}" if self.ts_ds and self.ts_qxs else self.ts_xzq or "未知"
    
    def to_dict(self) -> dict:
        """转换为字典"""
        result = super().to_dict()
        result['full_address'] = self.get_full_address()
        result['registration_time_display'] = self.get_registration_time_display()
        result['complaint_type_display'] = self.get_complaint_type_display()
        result['region_display'] = self.get_region_display()
        return result


class RegionalAnalysisResult(Base, TimestampMixin, ActiveMixin):
    """区域分析结果模型"""
    
    __tablename__ = "regional_analysis_result"
    
    # 关联
    petition_record_id = Column(String(100), ForeignKey('petition_record.xh'), nullable=False, comment="信访记录id")
    task_id = Column(Integer, ForeignKey('analysis_task.id'), nullable=False, comment="任务编号")
    
    # 基本信息
    ccjbz = Column(String(100), comment="初重件标志")
    tsr = Column(String(100), comment="姓名")
    xfnr = Column(String(2000), comment="投诉内容")
    ts_gk = Column(String(2000), comment="概况")
    ts_xzq = Column(String(100), comment="问题属地")
    ts_qxdw = Column(String(100), comment="去向单位")
    ts_dfnr = Column(String(2000), comment="答复内容")
    ts_bz = Column(String(1000), comment="备注")
    
    # 地址信息
    dzxx_tsdx = Column(String(1000), comment="投诉对象")
    dzxx_tsdz = Column(String(1000), comment="投诉地址")
    dzxx_ds = Column(String(100), comment="地址信息_行政区")
    dzxx_xzq = Column(String(100), comment="地址信息_行政区")
    dzxx_jd = Column(String(100), comment="地址信息_街道")
    dzxx_lng = Column(String(100), comment="地址信息_经度")
    dzxx_lat = Column(String(100), comment="地址信息_纬度")

    # 地址辅助信息
    dzxx_dx_words = Column(String(1000), comment="投诉对象的关键词")
    dzxx_dz_words = Column(String(1000), comment="投诉地址的关键词")
    
    # 重复分析
    cfxs_bh = Column(String(500), comment="重复编号")
    cfxs_gl = Column(String(100), comment="概率")
    
    # 关系
    # petition_record = relationship("PetitionRecord", back_populates="regional_analysis")
    # task = relationship("AnalysisTask")
    
    def has_location(self) -> bool:
        """检查是否有位置信息"""
        return self.dzxx_lng and self.dzxx_lat and self.dzxx_lng.strip() and self.dzxx_lat.strip()
    
    def get_location_coordinates(self) -> tuple:
        """获取位置坐标"""
        if self.has_location():
            try:
                return float(self.dzxx_lng), float(self.dzxx_lat)
            except ValueError:
                return None, None
        return None, None
    
    def get_confidence_score(self) -> float:
        """获取置信度分数"""
        if self.cfxs_gl:
            try:
                return float(self.cfxs_gl)
            except ValueError:
                return 0.0
        return 0.0
    
    def to_dict(self) -> dict:
        """转换为字典"""
        result = super().to_dict()
        result['has_location'] = self.has_location()
        result['location_coordinates'] = self.get_location_coordinates()
        result['confidence_score'] = self.get_confidence_score()
        return result


class ComplaintTypeAnalysisResult(Base, TimestampMixin, ActiveMixin):
    """投诉类型分析结果模型"""
    
    __tablename__ = "complaint_type_analysis_result"
    
    # 关联
    petition_record_id = Column(String(100), ForeignKey('petition_record.xh'), nullable=False, comment="信访记录id")
    task_id = Column(Integer, ForeignKey('analysis_task.id'), nullable=False, comment="任务编号")
    
    # 基本信息
    xfnr = Column(String(2000), comment="信访内容")
    
    # 地址信息
    dzxx_tsdx = Column(String(1000), comment="投诉对象")
    dzxx_tsdz = Column(String(1000), comment="投诉地址")
    dzxx_xzq = Column(String(100), comment="地址信息_行政区")
    dzxx_jd = Column(String(100), comment="地址信息_街道")
    dzxx_lng = Column(String(100), comment="地址信息_经度")
    dzxx_lat = Column(String(100), comment="地址信息_纬度")
    
    # 投诉类型
    tslx_yj = Column(String(100), comment="投诉类型-一级")
    tslx_yjyj = Column(String(2000), comment="投诉类型-一级判断依据")
    tslx_rj = Column(String(100), comment="投诉类型-二级")
    tslx_rjyj = Column(String(2000), comment="投诉类型-二级判断依据")
    tslx_sj = Column(String(100), comment="投诉类型-三级")
    tslx_sjyj = Column(String(2000), comment="投诉类型-三级判断依据")
    tslx_rj_zxd = Column(String(100), comment="投诉类型-二级-置信度（0%-100%）")
    tslx_sj_zxd = Column(String(100), comment="投诉类型-三级-置信度（0%-100%）")
    
    # 关系
    # petition_record = relationship("PetitionRecord", back_populates="complaint_type_analysis")
    # task = relationship("AnalysisTask")
    
    def get_full_complaint_type(self) -> str:
        """获取完整投诉类型"""
        parts = []
        if self.tslx_yj:
            parts.append(self.tslx_yj)
        if self.tslx_rj:
            parts.append(self.tslx_rj)
        if self.tslx_sj:
            parts.append(self.tslx_sj)
        return " -> ".join(parts)
    
    def get_level2_confidence(self) -> float:
        """获取二级类型置信度"""
        if self.tslx_rj_zxd:
            try:
                return float(self.tslx_rj_zxd.replace("%", "")) / 100
            except ValueError:
                return 0.0
        return 0.0
    
    def get_level3_confidence(self) -> float:
        """获取三级类型置信度"""
        if self.tslx_sj_zxd:
            try:
                return float(self.tslx_sj_zxd.replace("%", "")) / 100
            except ValueError:
                return 0.0
        return 0.0

    def get_confidence_score(self) -> float:
        """获取置信度分数 - 投诉类型分析返回最高级别的置信度"""
        return max(self.get_level2_confidence(), self.get_level3_confidence())

    def to_dict(self) -> dict:
        """转换为字典"""
        result = super().to_dict()
        result['full_complaint_type'] = self.get_full_complaint_type()
        result['level2_confidence'] = self.get_level2_confidence()
        result['level3_confidence'] = self.get_level3_confidence()
        return result


class SentimentAnalysisResult(Base, TimestampMixin, ActiveMixin):
    """情感分析结果模型"""
    
    __tablename__ = "sentiment_analysis_result"
    
    # 关联
    petition_record_id = Column(String(100), ForeignKey('petition_record.xh'), nullable=False, comment="信访记录id")
    task_id = Column(Integer, ForeignKey('analysis_task.id'), nullable=False, comment="任务编号")
    
    # 基本信息
    xfnr = Column(String(2000), comment="信访内容")
    
    # 地址信息
    dzxx_tsdx = Column(String(1000), comment="投诉对象")
    dzxx_tsdz = Column(String(1000), comment="投诉地址")
    dzxx_xzq = Column(String(100), comment="地址信息_行政区")
    dzxx_jd = Column(String(100), comment="地址信息_街道")
    dzxx_lng = Column(String(100), comment="地址信息_经度")
    dzxx_lat = Column(String(100), comment="地址信息_纬度")
    
    # 情感分析
    qgfx_lx = Column(String(100), comment="情感类型，重度")
    qgfx_pdly = Column(String(2000), comment="情感类型判断理由")
    qgfx_zy = Column(String(500), comment="摘要")
    qgfx_gjc = Column(String(1000), comment="关键词")
    
    # 关系
    # petition_record = relationship("PetitionRecord", back_populates="sentiment_analysis")
    # task = relationship("AnalysisTask")
    
    def get_sentiment_level(self) -> str:
        """获取情感级别"""
        sentiment_map = {
            "neutral": "中性",
            "mild_anger": "轻度不满",
            "moderate_anger": "中度不满", 
            "severe_anger": "重度不满"
        }
        return sentiment_map.get(self.qgfx_lx, self.qgfx_lx or "未知")
    
    def get_keywords_list(self) -> list:
        """获取关键词列表"""
        if self.qgfx_gjc:
            return [keyword.strip() for keyword in self.qgfx_gjc.split(",") if keyword.strip()]
        return []

    def get_sentiment_intensity(self) -> float:
        """获取情感强度分数 - 基于情感类型返回强度"""
        intensity_map = {
            "neutral": 0.0,
            "mild_anger": 1.0,
            "moderate_anger": 2.0,
            "severe_anger": 3.0
        }
        return intensity_map.get(self.qgfx_lx, 0.0)

    def get_sentiment_label(self) -> str:
        """获取情感标签 - 与get_sentiment_level方法相同"""
        return self.get_sentiment_level()

    def get_confidence_score(self) -> float:
        """获取置信度分数 - 情感分析默认返回0.8"""
        return 0.8

    def to_dict(self) -> dict:
        """转换为字典"""
        result = super().to_dict()
        result['sentiment_level'] = self.get_sentiment_level()
        result['keywords_list'] = self.get_keywords_list()
        return result


class ComplianceAnalysisResult(Base, TimestampMixin, ActiveMixin):
    """规范性分析结果模型"""
    
    __tablename__ = "compliance_analysis_result"
    
    # 关联
    petition_record_id = Column(String(100), ForeignKey('petition_record.xh'), nullable=False, comment="信访记录id")
    task_id = Column(Integer, ForeignKey('analysis_task.id'), nullable=False, comment="任务编号")
    
    # 基本信息
    xfnr = Column(String(2000), comment="信访内容")
    ts_qxdw = Column(String(1000), comment="去向单位")

    # 地址信息
    dzxx_tsdx = Column(String(1000), comment="投诉对象")
    dzxx_tsdz = Column(String(1000), comment="投诉地址")
    dzxx_xzq = Column(String(100), comment="地址信息_行政区")
    dzxx_jd = Column(String(100), comment="地址信息_街道")
    dzxx_lng = Column(String(100), comment="地址信息_经度")
    dzxx_lat = Column(String(100), comment="地址信息_纬度")
    
    # 规范性分析
    gffx_dfnr = Column(String(2000), comment="答复内容")
    gffx_zt = Column(String(100), comment="是否规范：1：合规、0：不合规")
    gffx_pdly = Column(String(500), comment="判断理由")
    
    # 关系
    # petition_record = relationship("PetitionRecord", back_populates="compliance_analysis")
    # task = relationship("AnalysisTask")
    
    def is_compliant(self) -> bool:
        """检查是否合规"""
        return self.gffx_zt == "1"
    
    def get_compliance_status(self) -> str:
        """获取合规状态"""
        if self.gffx_zt == "1":
            return "合规"
        elif self.gffx_zt == "0":
            return "不合规"
        else:
            return "未分析"

    def get_confidence_score(self) -> float:
        """获取置信度分数 - 规范性分析默认返回1.0"""
        return 1.0

    def to_dict(self) -> dict:
        """转换为字典"""
        result = super().to_dict()
        result['is_compliant'] = self.is_compliant()
        result['compliance_status'] = self.get_compliance_status()
        return result


class DuplicateAnalysisResult(Base, TimestampMixin, ActiveMixin):
    """重复分析结果模型"""
    
    __tablename__ = "duplicate_analysis_result"
    
    # 基本信息
    bh = Column(String(100), comment="序号，记录编号，无实际用途")
    task_id = Column(Integer, ForeignKey('analysis_task.id'), nullable=False, comment="任务编号")
    
    # 重复分析
    cfbh = Column(String(100), comment="重复编号（对应的重复信访内容，编号唯一）")
    xfxh = Column(String(100), comment="信访的初件编号（信访的索引项）")
    
    # 关系
    # task = relationship("AnalysisTask")

    def get_confidence_score(self) -> float:
        """获取置信度分数 - 重复分析默认返回1.0"""
        return 1.0

    def to_dict(self) -> dict:
        """转换为字典"""
        result = super().to_dict()
        return result